<template>
    <div class="app-container">
        <el-form :model="queryParams"
                 ref="queryForm"
                 :inline="true"
                 v-show="showSearch"
                 label-width="80px"
        >
            <el-form-item label="电表编号" prop="sn">
                <el-input
                    v-model="queryParams.sn"
                    placeholder="请输入电表编号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <!--            <el-col :span="1.5">-->
            <!--                <el-button-->
            <!--                    plain-->
            <!--                    size="mini"-->
            <!--                    @click="handleTransfer"-->
            <!--                >转移电表-->
            <!--                </el-button>-->
            <!--            </el-col>-->
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="warning"-->
            <!--          plain-->
            <!--          icon="el-icon-download"-->
            <!--          size="mini"-->
            <!--          @click="handleExport"-->
            <!--          v-hasPermi="['business:flowCard:export']"-->
            <!--        >导出</el-button>-->
            <!--      </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="electricityList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="电表名称" align="center" prop="name"/>
            <el-table-column label="是否在线" align="center" prop="online">
                <template slot-scope="scope">
                    <dict-tag2 :type="DICT_TYPE.BIZ_DEVICE_ONLINE" :value="scope.row.online"/>
                </template>
            </el-table-column>
            <el-table-column label="电表编号" align="center" prop="sn"/>
            <!--            <el-table-column label="电费单价" align="center" prop="unitPrice"/>-->
            <el-table-column label="剩余电量(度)" align="center" prop="surplus">
                <template slot-scope="scope">
                    {{ scope.row.electricMeterMode === 0 ? scope.row.surplus : '--' }}
                </template>
            </el-table-column>
            <el-table-column label="总电量(度)" align="center" prop="totalElectricity"/>
            <el-table-column label="欠费停电" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.biz_owe_stop" :value="scope.row.oweStop"/>
                </template>
            </el-table-column>
            <el-table-column label="电表状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag2 :type="DICT_TYPE.BIZ_ELECTRICITY_STATUS" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="电表模式" align="center" prop="electricMeterMode">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.biz_electricity_mode" :value="scope.row.electricMeterMode"/>
                </template>
            </el-table-column>
            <el-table-column label="设备型号" align="center" prop="status">
                <template slot-scope="scope">
                    <span>{{ scope.row.deviceModel.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdate(scope.row)"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleDelete(scope.row)"
                    >删除
                    </el-button>
                    <el-dropdown size="medium" @command="(command) => handleCommand(command, scope.row)"
                    >
                        <span class="el-dropdown-link">更多</span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleReading">抄表</el-dropdown-item>
                            <el-dropdown-item command="handleSwitchStatus" v-if="scope.row.switchStatus === '0'"
                                              style="color:sandybrown"
                            >强制拉闸
                            </el-dropdown-item>
                            <el-dropdown-item command="handleSwitchStatus" v-if="scope.row.switchStatus === '1'"
                                              style="color:#67c23a"
                            >解除拉闸
                            </el-dropdown-item>
                            <!--                            <el-dropdown-item command="handleSchedule">定时</el-dropdown-item>-->
                            <!--                            <el-dropdown-item command="handlePay">充值</el-dropdown-item>-->
                            <el-dropdown-item command="handleDetail">明细</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改流量卡信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
                <el-form-item label="电表名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入电表名称"/>
                </el-form-item>

                <el-form-item label="电表编号" prop="sn">
                    <el-input v-model="form.sn" placeholder="请输入电表编号"/>
                </el-form-item>

                <!--                <el-form-item label="电表单价" prop="unitPrice">-->
                <!--                    <el-input v-model="form.unitPrice" placeholder="请输入电表单价"/>-->
                <!--                </el-form-item>-->

                <el-form-item label="欠费停电" prop="oweStop">
                    <el-select v-model="form.oweStop">
                        <el-option
                            v-for="item in dict.type.biz_owe_stop"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择电表状态">
                        <el-option
                            v-for="item in dict.type.biz_electricity_status"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="电表模式" prop="electricMeterMode">
                    <el-select v-model="form.electricMeterMode" placeholder="请选择电表模式">
                        <el-option
                            v-for="item in dict.type.biz_electricity_mode"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="设备型号" prop="electricMeterMode">
                    <el-select v-model="form.deviceModelId" placeholder="请选择设备型号" filterable>
                        <el-option
                            v-for="item in deviceModelList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!--        定时任务-->
        <ScheduleForm ref="scheduleDig" @success="getList"></ScheduleForm>
        <PayForm ref="payDig" @success="getList"></PayForm>
        <TransferForm ref="transferDig" @success="getList"></TransferForm>
    </div>
</template>

<script>

import {
    addElectricity,
    listElectricity,
    updateElectricity,
    delElectricity,
    getElectricity,
    readingElectricMeter,
    forceoffElectricMeter
} from '@/api/equipment/electricity'
import { getSimpleDeviceModelList } from '@/api/equipment/deviceModel'
import { genUUID } from '@/utils/ruoyi'
import ScheduleForm from '@/views/equipment/electricity/dialog/ScheduleForm.vue'
import PayForm from '@/views/equipment/electricity/dialog/PayForm.vue'
import TransferForm from '@/views/equipment/electricity/dialog/TransferForm.vue'
import { getDictDatas, DICT_TYPE } from '@/utils/dictNew'

export default {
    name: 'electricity',
    components: {
        ScheduleForm,
        PayForm,
        TransferForm
    },
    dicts: ['biz_electricity_status', 'biz_electricity_mode', 'biz_owe_stop', 'biz_device_online'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 信息表格数据
            electricityList: [],
            // 设备型号列表
            deviceModelList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                id: null,
                name: null,
                sn: null,
                unitPrice: null,
                sort: null,
                status: null,
                oweStop: null,
                deviceModelId: null,
                areaId: null,
                electricMeterMode: null
            },
            // 表单参数
            form: {},
            webClientId: genUUID(),
            // 超时时间实例
            timer: null,
            // 判断是否打开连接
            isOpen: false,
            //心跳定时器实例
            heartTime: null,
            // 定义控制是否是第一次点击抄表或者拉闸
            isFirstHandle: false,
            // 定义连接的状态
            readyStatus: 0,
            // websocket 实例
            websocket: null,
            // socket地址
            socketUrl: '',
            // 心跳次数
            socketHeart: 0,
            // 心跳超时时间
            HeartTimeOut: 3000,
            // 错误次数
            socketError: 0,
            // 提示信息
            text: '',
            // 表单校验
            rules: {}
        }
    },
    created() {
        this.getList()
        this.getDeviceModelList()
    },
    methods: {

        getList() {
            this.loading = true
            listElectricity(this.queryParams).then(response => {
                this.electricityList = response.data.list
                this.total = response.data.total
                this.loading = false
            })
        },

        // 获取设备型号
        getDeviceModelList() {
            getSimpleDeviceModelList().then(res => {
                console.log(res)
                this.deviceModelList = res.data
            })
        },
        cancel() {
            this.open = false
            this.reset()
        },

        reset() {
            this.form = {
                id: null,
                name: null,
                sn: null,
                unitPrice: null,
                status: null,
                oweStop: null,
                sort: null,
                deviceModelId: null,
                areaId: null,
                electricMeterMode: null
            }
            this.resetForm('form')
        },

        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },

        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加电表信息'
        },

        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getElectricity(id).then(response => {
                this.form = response.data
                this.form.status = this.form.status + ''
                this.form.electricMeterMode = this.form.electricMeterMode + ''
                this.open = true
                this.title = '修改电表信息'
            })
        },
        // 更多
        handleCommand(command, row) {
            switch (command) {
                case 'handlePay':
                    this.handlePay(row)
                    break
                case 'handleSchedule':
                    this.handleSchedule(row)
                    break
                case 'handleReading':
                    this.handleReading(row)
                    break
                case 'handleSwitchStatus':
                    this.handleSwitchStatus(row)
                    break
                case 'handleDetail':
                    this.handleDetail(row)
                    break
                default:
                    break
            }
        },
        /** 明细操作 */
        handleDetail(row) {
            this.$router.push({
                path: '/electricity/detail',
                query: { row }
            })
        },
        /** 充值按钮操作 */
        handlePay(row) {
            this.$refs.payDig.open(row)
        },
        /** 定时操作 */
        handleSchedule(row) {
            this.$refs.scheduleDig.open(row)
        },
        /* 转移电表 */
        handleTransfer() {
            this.$refs.transferDig.open()
        },
        /** 抄表 */
        handleReading(row) {
            clearInterval(this.heartTime)
            let obj = {
                sn: row.sn,
                clientId: this.webClientId
            }
            this.loading = true
            this.getTimer()
            readingElectricMeter(obj).then(res => {
                if (res) {
                    this.text = '抄表成功'
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                    // this.sendWebsocketMessage(this.webClientId)
                }
            }, error => {
                this.resetTime()
            })
        },
        /** 强制拉闸-解除拉闸 */
        handleSwitchStatus(row) {
            let switchStatus
            this.getTimer()
            if (row.switchStatus === '0') {
                switchStatus = '1'
                this.text = '拉闸成功'
            } else {
                switchStatus = '0'
                this.text = '解除成功'
            }
            let obj = {
                sn: row.sn,
                clientId: this.webClientId,
                switchStatus
            }
            this.loading = true
            this.isFirstHandle = true
            forceoffElectricMeter(obj).then(res => {
                if (res) {
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
            }, error => {
                this.resetTime()
            })
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('exist')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('exist')
                    return
                }

                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)
            let data = {}
            try {
                data = JSON.parse(json)
                console.log('data', data)
                let data2 = JSON.parse(data.data)
                if (data2.code === 200) {
                    let typeList = [1, 2, 3]
                    if (data2.data.type === 1) {
                        for (let item of this.electricityList) {
                            if (item.sn === data2.data.sn) {
                                item.status = data2.data.status
                                item.switchStatus = data2.data.switchStatus
                            }
                        }
                    }
                    if (typeList.includes(data2.data.type)) {
                        this.loading = false
                        if (data2.data.type !== 1) {
                            this.getList()
                        }
                        this.$message.success(this.text)
                        clearInterval(this.timer)
                    }
                }
            } catch (e) {
            }
        },
        getTimer() {
            let loadingTime = 30
            let that = this
            this.timer = setInterval(() => {
                if (loadingTime <= 0) {
                    that.resetTime()
                } else {
                    // loadingText.value = loadingTime+ 's'
                    --loadingTime
                }
            }, 1000)
        },
        // 重置
        resetTime() {
            clearInterval(this.timer)
            // this.loading.close()
            this.loading = false
            this.$message.error('系统繁忙，请稍后再试')
        },
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateElectricity(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addElectricity(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除设备').then(function() {
                return delElectricity(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('system/card/export', {
                ...this.queryParams
            }, `card_${new Date().getTime()}.xlsx`)
        }
    }
}
</script>
